Skip to content

feat(frontend): cooperative-page #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jan 8, 2025
Merged

feat(frontend): cooperative-page #37

merged 7 commits into from
Jan 8, 2025

Conversation

tractorss
Copy link
Contributor

@tractorss tractorss commented Jan 7, 2025

Summary by CodeRabbit

  • New Features

    • Added a new Cooperative page with sections for Hero, Members, and Reports.
    • Introduced a new LearnMore component for additional information display.
    • Created a DropdownContainer for selecting report parameters.
    • Added a ReportCard component to showcase individual reports.
    • Introduced a Dropdown component for improved item selection.
    • Added a new Hero component for the cooperative page layout.
  • Improvements

    • Enhanced page navigation and user interaction with new components.
    • Implemented type-safe GraphQL queries for data fetching.
  • Changes

    • Renamed ForBuilders page to Community.
    • Updated component structures and styling.
    • Modified the Button component to include a new tertiary style variant.

Copy link
Contributor

coderabbitai bot commented Jan 7, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces a comprehensive set of components and types for the Cooperative page in a React-based web application. The changes include creating new React components like Hero, MemberSection, ReportSection, and supporting components such as LearnMore, ReportCard, and DropdownContainer. Accompanying these components are GraphQL queries and TypeScript type definitions that define the data structure for fetching and rendering the page content. The implementation focuses on modular, type-safe components with responsive design using Tailwind CSS.

Changes

File Change Summary
frontend/src/components/Cooperative/... Added new components: Hero, MemberSection, LearnMore, ReportSection, ReportCard, DropdownContainer
frontend/src/components/Dropdown/... Introduced Dropdown and DropdownItemButton components for interactive dropdown functionality
frontend/src/pages/... Renamed ForBuilders to Community, created new Cooperative page component
frontend/src/queries/cooperative/... Added GraphQL queries and TypeScript types for hero, member section, and report section data
frontend/.husky/pre-commit Updated pre-commit hook to use yarn lint --fix
frontend/src/components/Button.tsx Added a new tertiary style variant to the Button component
frontend/src/components/ExternalLink.tsx Updated class name handling using clsx for better management

Possibly related PRs

  • feat(frontend): cooperative-page #37: The LearnMore component was introduced in this PR, which is directly related to the main PR as it involves the same component and file (frontend/src/components/Cooperative/MemberSection/LearnMore.tsx).
  • Refactor(frontend)/cooperative page #39: This PR includes modifications to the cooperative.tsx file, which is relevant as it may involve the integration of components like LearnMore and MemberSection that are part of the main PR.

Suggested reviewers

  • Harman-singh-waraich

Poem

🐰 In the realm of code, a new page unfolds
Components dance, their stories untold
Dropdowns click, reports take flight
Cooperative magic, shining so bright!
A rabbit's delight, this digital art 🌈


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cc78953 and 5ccaa75.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (11)
  • frontend/.husky/pre-commit (1 hunks)
  • frontend/src/components/Button.tsx (1 hunks)
  • frontend/src/components/Cooperative/MemberSection/LearnMore.tsx (1 hunks)
  • frontend/src/components/Cooperative/ReportSection/DropdownContainer.tsx (1 hunks)
  • frontend/src/components/Cooperative/ReportSection/ReportCard.tsx (1 hunks)
  • frontend/src/components/Cooperative/ReportSection/index.tsx (1 hunks)
  • frontend/src/components/Cooperative/hero.tsx (1 hunks)
  • frontend/src/components/Dropdown/DropdownItemButton.tsx (1 hunks)
  • frontend/src/components/Dropdown/index.tsx (1 hunks)
  • frontend/src/components/ExternalLink.tsx (2 hunks)
  • frontend/src/pages/cooperative.tsx (1 hunks)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Jan 7, 2025

Deploy Preview for kleros-website-v2 failed. Why did it fail? →

Name Link
🔨 Latest commit 5ccaa75
🔍 Latest deploy log https://app.netlify.com/sites/kleros-website-v2/deploys/677ea7837b23a50008c82eba

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (21)
frontend/src/queries/cooperative/hero.ts (1)

4-4: Remove unnecessary empty line

Consider removing the extra empty line to maintain consistent spacing.

frontend/src/components/Dropdown/DropdownItemButton.tsx (2)

4-6: Fix typo in style variable name

The variable name contains a typo: dropwdownItemBaseStyle should be dropdownItemBaseStyle.


12-16: Consider adding prop validation

The interface looks good, but consider adding prop-types validation for runtime type checking, especially for required props.

frontend/src/components/Cooperative/ReportSection/index.tsx (2)

13-22: Consider simplifying the report type selection

The switch statement could be simplified using an object lookup pattern for better maintainability.

-  const getReports = (reportType: ReportType) => {
-    switch (reportType) {
-      case "annual":
-        return reportsData.annualReports;
-      case "risk":
-        return reportsData.riskReports;
-      default:
-        return reportsData.treasuryReports;
-    }
-  };
+  const reportTypeMap = {
+    annual: reportsData.annualReports,
+    risk: reportsData.riskReports,
+    treasury: reportsData.treasuryReports,
+  };
+  const getReports = (reportType: ReportType) => 
+    reportTypeMap[reportType] ?? reportTypeMap.treasury;

12-34: Consider adding error boundary and prop validation

The component could benefit from:

  1. An error boundary to handle potential data issues
  2. Explicit prop spreading instead of using the spread operator to avoid prop pollution
  3. Prop-types validation for runtime type checking
frontend/src/components/Cooperative/MemberSection/LearnMore.tsx (2)

16-16: Replace hardcoded z-index values with CSS variables

Using hardcoded z-index values (z-[1]) makes it difficult to maintain stacking context. Consider using CSS variables for better maintainability.

-      <h2 className="text-primary-text text-xl mb-8 z-[1]">{title}</h2>
+      <h2 className="text-primary-text text-xl mb-8 z-content">{title}</h2>

Also applies to: 21-21, 24-24


28-30: Use background.name for Image alt text

The alt text is hardcoded. Consider using background.name from props for better accessibility.

-        alt="Learn more Image Background"
+        alt={background.name}
frontend/src/components/Cooperative/MemberSection/index.tsx (3)

5-7: Remove Hungarian notation from interface name

The I prefix (Hungarian notation) is not recommended in modern TypeScript. Consider renaming to just MemberSectionProps.

-interface IMemberSection {
+interface MemberSectionProps {
   memberData: CooperativePageMemberQueryType["cooperativePageMemberSection"];
 }

16-16: Avoid spreading props blindly

Spreading props ({...memberData.learnMoreSection}) can pass unwanted props. Consider explicit prop passing for better type safety and maintainability.

-      <LearnMore {...memberData.learnMoreSection} />
+      <LearnMore
+        title={memberData.learnMoreSection.title}
+        button={memberData.learnMoreSection.button}
+        background={memberData.learnMoreSection.background}
+      />

23-23: Avoid className overrides with !important

The !gap-2 className uses Tailwind's important modifier. Consider adjusting the ExternalLink component's base styles instead.

frontend/src/pages/community.tsx (1)

Line range hint 31-44: Remove redundant property name in getStaticProps

The heroData: heroData assignment is redundant due to object property shorthand in modern JavaScript.

   return {
     props: {
       navbarData,
       footerData,
-      heroData: heroData,
+      heroData,
     },
   };
frontend/src/queries/cooperative/report-section.ts (3)

34-49: Extract common fields into a base type

The report types (annualReports, riskReports, treasuryReports) share common fields. Consider extracting them into a base type.

type BaseReport = {
  url: string;
  year: number;
};

type MonthlyReport = BaseReport & {
  month: string;
};

export type CooperativePageReportQueryType = {
  cooperativePageReportSection: {
    reports: Report[];
  };
  annualReports: BaseReport[];
  riskReports: MonthlyReport[];
  treasuryReports: MonthlyReport[];
};

3-15: Add JSDoc comments for exported types

The exported types lack documentation. Consider adding JSDoc comments to improve code maintainability.

/** Type of report that can be displayed */
export type ReportType = "annual" | "risk" | "treasury";

/** Structure of a report item with its metadata */
export type Report = {
  title: string;
  // ... rest of the type
};

17-51: Consider breaking down the GraphQL query

The query could be split into smaller fragments for better reusability and maintainability.

const reportFragment = gql`
  fragment ReportFields on Report {
    title
    subtitle
    reportType
    yearDropdownLabel
    monthDropdownLabel
    downloadButtonText
    icon {
      name
      url
    }
  }
`;

export const cooperativePageReportQuery = gql`
  {
    cooperativePageReportSection {
      reports {
        ...ReportFields
      }
    }
    # ... rest of the query
  }
  ${reportFragment}
`;
frontend/src/components/Cooperative/ReportSection/ReportCard.tsx (1)

9-17: Consider adding type constraints for the month field.

The month field in Reports type could benefit from being more specific about the expected format (e.g., full month name, abbreviated month, or numeric).

 export type Reports = {
   url: string;
-  month?: string;
+  month?: 'January' | 'February' | 'March' | 'April' | 'May' | 'June' | 
+          'July' | 'August' | 'September' | 'October' | 'November' | 'December';
   year: number;
 }[];
frontend/src/components/Cooperative/hero.tsx (2)

23-37: Enhance button accessibility for external links.

When opening links in new tabs, it's important to inform screen reader users.

 {buttons.map((button) => (
   <Link
     key={button.text}
     href={button.link.url}
     target="_blank"
     rel="noopener noreferrer"
+    aria-label={`${button.text} (opens in new tab)`}
   >
     <Button
       variant="secondary"
       className=" hover:!bg-primary-blue hover:!border-primary-blue hover:!text-background-2"
     >
       <span>{button.text}</span>
     </Button>
   </Link>
 ))}

45-50: Optimize hero background image loading.

Consider adding priority and quality props to optimize the hero image loading performance.

 <Image
   src={background.url}
   alt="Hero Image Background"
   fill
+  priority
+  quality={90}
   className="absolute top-0 left-0 h-full z-[-1] object-cover"
 />
frontend/src/components/Dropdown/index.tsx (1)

36-49: Improve event handler type safety.

Replace any with proper MouseEvent type for better type safety.

 useEffect(() => {
-  // eslint-disable-next-line @typescript-eslint/no-explicit-any
-  const handleClickOutside = (event: any) => {
+  const handleClickOutside = (event: MouseEvent) => {
     if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
       setIsOpen(false);
     }
   };

   document.addEventListener("mousedown", handleClickOutside);
   return () => {
     document.removeEventListener("mousedown", handleClickOutside);
   };
 }, []);
frontend/src/components/Cooperative/ReportSection/DropdownContainer.tsx (3)

18-19: Consider initializing state with meaningful default values

The undefined initial states could lead to uncontrolled components initially. Consider:

  1. Initializing with the most recent year from reports
  2. Setting the first available month for that year
-  const [year, setYear] = useState<number>();
-  const [month, setMonth] = useState<string>();
+  const [year, setYear] = useState<number>(() => 
+    Math.max(...Array.from(reports.map(r => r.year)))
+  );
+  const [month, setMonth] = useState<string>(() => {
+    const reportsForYear = reports.filter(r => r.year === year);
+    return reportsForYear[0]?.month || '';
+  });

52-61: Consider moving monthOrder near its usage

The month sorting logic relies on monthOrder array defined at the bottom of the file. Consider:

  1. Moving monthOrder declaration above its usage
  2. Making it a constant using as const for better type safety
+ const monthOrder = [
+   "January", "February", "March", "April", "May", "June",
+   "July", "August", "September", "October", "November", "December"
+ ] as const;
+
  const months = useMemo(
    () =>
      Array.from(new Set(monthsSet))
        .sort((a, b) => monthOrder.indexOf(a) - monthOrder.indexOf(b))
        .map((month) => ({
          key: month,
          value: month,
        })),
    [monthsSet]
  );

101-115: Consider using named exports

For better maintainability and import/export tracking:

- export default DropdownContainer;
+ export { DropdownContainer };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bb3a393 and cc78953.

⛔ Files ignored due to path filters (1)
  • frontend/src/assets/svgs/icons/down-arrow-blue.svg is excluded by !**/*.svg
📒 Files selected for processing (13)
  • frontend/src/components/Cooperative/MemberSection/LearnMore.tsx (1 hunks)
  • frontend/src/components/Cooperative/MemberSection/index.tsx (1 hunks)
  • frontend/src/components/Cooperative/ReportSection/DropdownContainer.tsx (1 hunks)
  • frontend/src/components/Cooperative/ReportSection/ReportCard.tsx (1 hunks)
  • frontend/src/components/Cooperative/ReportSection/index.tsx (1 hunks)
  • frontend/src/components/Cooperative/hero.tsx (1 hunks)
  • frontend/src/components/Dropdown/DropdownItemButton.tsx (1 hunks)
  • frontend/src/components/Dropdown/index.tsx (1 hunks)
  • frontend/src/pages/community.tsx (2 hunks)
  • frontend/src/pages/cooperative.tsx (1 hunks)
  • frontend/src/queries/cooperative/hero.ts (1 hunks)
  • frontend/src/queries/cooperative/member-section.ts (1 hunks)
  • frontend/src/queries/cooperative/report-section.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules - kleros-website-v2
  • GitHub Check: Header rules - kleros-website-v2
  • GitHub Check: Pages changed - kleros-website-v2
🔇 Additional comments (9)
frontend/src/queries/cooperative/hero.ts (1)

5-27: LGTM! Well-structured GraphQL query with matching TypeScript types

The type definitions accurately match the GraphQL query structure, and the reuse of the ArrowLink type promotes consistency across the application.

Also applies to: 29-44

frontend/src/components/Dropdown/DropdownItemButton.tsx (1)

17-32: LGTM! Clean implementation of dropdown item button

The component is well-structured with proper type safety and clean conditional styling using clsx.

frontend/src/queries/cooperative/member-section.ts (1)

5-49: LGTM! Well-organized types and query structure

The implementation shows good type safety with proper reuse of the ArrowLink type and clean hierarchy between types and GraphQL query structure.

frontend/src/components/Cooperative/MemberSection/LearnMore.tsx (1)

15-15: Add explicit dimensions to the parent container

The Image component uses fill prop but the parent container lacks explicit dimensions, which may cause layout issues. Add height/width to the parent div.

-    <div className="relative w-full flex flex-col items-center justify-center mt-16 p-8 ">
+    <div className="relative w-full h-[300px] flex flex-col items-center justify-center mt-16 p-8 ">

Also applies to: 27-32

frontend/src/pages/community.tsx (1)

45-45: LGTM! Component renaming improves clarity

The renaming from ForBuilders to Community better reflects the component's purpose.

frontend/src/components/Cooperative/ReportSection/ReportCard.tsx (1)

53-55: LGTM! Well-implemented responsive image.

The Image component is properly configured with fill property and appropriate parent container dimensions.

frontend/src/components/Cooperative/ReportSection/DropdownContainer.tsx (3)

1-10: Well-structured type definitions and imports!

The interface is properly defined using TypeScript's Pick utility type, ensuring type safety for the component props.


73-98: Well-structured and accessible render logic!

The component demonstrates good practices:

  • Responsive layout using Tailwind CSS
  • Proper accessibility with labels
  • Clean conditional rendering

1-115: Verify edge cases and performance

Please ensure thorough testing of:

  1. Behavior when reports array is empty
  2. Performance with large numbers of reports
  3. Correct handling of invalid year/month combinations
✅ Verification successful

Implementation is robust and well-designed

The component already handles the mentioned concerns effectively:

  • Empty reports are handled safely through Set operations
  • Performance is optimized with useMemo for large datasets
  • Type safety and controlled inputs prevent invalid combinations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test coverage of this component
fd -e test.tsx -e spec.tsx -e test.ts -e spec.ts . | xargs rg "DropdownContainer"

Length of output: 629


Script:

#!/bin/bash
# Search for ReportCard tests and implementation
fd "ReportCard" . -e test.tsx -e spec.tsx -e test.ts -e spec.ts | xargs cat

# Examine error handling in ReportCard
rg -A 10 "reports.*=" frontend/src/components/Cooperative/ReportSection/ReportCard.tsx

Length of output: 164


Script:

#!/bin/bash
# Check for error boundaries and type definitions
rg -l "ErrorBoundary" frontend/src/components/Cooperative/ReportSection/

# Examine Report type definition
cat frontend/src/queries/cooperative/report-section.ts

# Check component's error handling
rg -A 5 "catch|throw|error" frontend/src/components/Cooperative/ReportSection/DropdownContainer.tsx

Length of output: 1369

Copy link
Collaborator

@alcercu alcercu left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants